﻿using mars_client.csharp.cache;
using mars_client.csharp.enums;
using mars_client.csharp.model;
using mars_client.csharp.util;
using mars_client.csharp.vo;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace mars_client.csharp.radar
{
    class Radar
    {
        // 单例模式
        private Radar(){}
        private readonly static Radar instance = new Radar();
        internal static Radar Instance
        {
            get
            {
                if(instance.ss == null)
                {
                    TcpClient client = new TcpClient();
                    try
                    {
                        client.Connect(IPAddress.Parse("172.20.10.2"), 10223);
                        MessageBox.Show("连接成功");
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("远程主机无响应");
                        MessageBox.Show(e.ToString());
                    }
                    instance.ss = new ServerSocket(client);
                    instance.receiveData();
                    instance.heartBeat();
                }
                return instance;
            }
        }
        /***************************************/
        private ServerSocket ss;
        MessageCache mc = MessageCache.Instance;
        public void sendData(Object o)
        {
            Task.Run(() =>
            {
                ss.Bw.Write(TransformUtil.ObjectToBytes(o));
            });
        }

        private void receiveData()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    byte[] bytes;
                    if (ss.Client.Available > 0)
                    {
                        bytes = ss.Br.ReadBytes(ss.Client.Available);
                        //MessageBox.Show(JsonConvert.SerializeObject(TransformUtil.bytesToObject(bytes)));
                        LogUtil.console(JsonConvert.SerializeObject(TransformUtil.bytesToObject(bytes)));
                        mc.setMessage(TransformUtil.J2O<MessageCO>(TransformUtil.bytesToObject(bytes)));
                    }
                }
            });
        }

        private void heartBeat()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    MessageCO messageCO = new MessageCO();
                    messageCO.type = (int)RequestEnum.request.HeartBeats;
                    instance.sendData(messageCO);
                    Thread.Sleep(30000);
                }
            });
        }
    }
}
